package cmd

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/template-single/internal/ker/mod"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"

	"github.com/gogf/template-single/internal/controller/hello"
)

var (
	S    *ghttp.Server
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			config, err := gcfg.New()
			if err != nil {
				return err
			}
			ip := config.MustGet(ctx, "modbus.ip")
			port := config.MustGet(ctx, "modbus.port")
			mod.Am, err = mod.New(ip.String(), port.String())
			if err != nil {
				fmt.Println(err.Error())
				return err
			}
			err = mod.Am.Client.Open()
			if err != nil {
				fmt.Println(err.Error())
				return err
			}
			s := g.Server()
			s.Group("/", func(group *ghttp.RouterGroup) {
				group.Middleware(ghttp.MiddlewareHandlerResponse)
				group.Bind(
					hello.NewV1(),
				)
			})
			S = s
			return s.Start()
		},
	}
)
